//
//  MapLBS.m
//  carcareIOS
//
//  Created by ileo on 16/8/17.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "MapLBS.h"
#import "CommonUtility.h"

#define ID_STORE @"id_store"

@interface MapLBS ()

@property (nonatomic, copy) NSArray<LocAnnotation *> *annotations;

@end

@implementation MapLBS


-(void)setStoreModels:(NSArray<LBSStoreModel *> *)storeModels{
    _storeModels = storeModels;
    
    NSMutableArray<LocAnnotation *> *tmp = [NSMutableArray arrayWithCapacity:storeModels.count];
    [storeModels enumerateObjectsUsingBlock:^(LBSStoreModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LocAnnotation *annotation = [[LocAnnotation alloc] initWithCoordinate:obj.coordinate];
        annotation.tag = idx;
        annotation.identifier = ID_STORE;
        [tmp addObject:annotation];
        DLog(@"%f %f",obj.coordinate.latitude,obj.coordinate.longitude);

    }];
    [self dissmissStoreMap];
    self.annotations = [tmp copy];
    
    if (self.coordinate.latitude != 0) {
        [tmp addObject:[[LocAnnotation alloc] initWithCoordinate:self.coordinate]];
    }
    CGFloat gap = 100;
    
    DLog(@"%f %f",self.coordinate.latitude,self.coordinate.longitude);
    
    if (tmp.count > 1) {
        [self.mapView setVisibleMapRect:[CommonUtility minMapRectForAnnotations:tmp] edgePadding:UIEdgeInsetsMake(gap, gap, gap, gap) animated:NO];
    }else if (tmp.count == 1) {
        [self.mapView setCenterCoordinate:tmp[0].coordinate animated:NO];
    }


}

-(void)showStoreMap{
    [self.mapView addAnnotations:self.annotations];
}
- (void)dissmissStoreMap
{
    [self.mapView removeAnnotations:self.annotations];
}
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[LocAnnotation class]]) {
        LocAnnotation *ann = (LocAnnotation *)annotation;
        if ([ann.identifier isEqualToString:ID_STORE]) {
            LocAnnotationView *annotationView = [[LocAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ID_STORE];
            
            __weak __typeof(self) wself = self;
            annotationView.image = ImageNamed(@"lbs_store");
            annotationView.Select = ^(){
                if (wself.Select) {
                    wself.Select(wself.storeModels[ann.tag]);
                }
                [wself.mapView removeAnnotations:wself.annotations];
                [wself showStoreMap];
                [wself.mapView setCenterCoordinate:ann.coordinate animated:YES];
                [wself.mapView setZoomLevel:15 atPivot:[wself.mapView convertCoordinate:ann.coordinate toPointToView:wself.mapView] animated:YES];
            };
            
            annotationView.annotation = annotation;
            annotationView.canShowCallout = NO;
            return annotationView;
        }
    }
    
    return [super mapView:mapView viewForAnnotation:annotation];
}

@end
